<template>
  <div class="match-records-table">
    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="matchList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="匹配状态" width="120">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.matchStatus || scope.row.matchResult)">
            {{ scope.row.matchStatus || scope.row.matchResult }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" min-width="120" prop="orderNumber"></el-table-column>
      <el-table-column label="收货单编号" min-width="120" prop="receiptNumber"></el-table-column>
      <el-table-column label="发票编号" min-width="120" prop="invoiceNumber"></el-table-column>
      <el-table-column label="供应商" min-width="150" prop="supplierName"></el-table-column>
      <el-table-column label="订单金额" min-width="120">
        <template #default="scope">
          {{ formatCurrency(scope.row.orderAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="收货单金额" min-width="120">
        <template #default="scope">
          {{ formatCurrency(scope.row.receiptAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="发票金额" min-width="120">
        <template #default="scope">
          {{ formatCurrency(scope.row.invoiceAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="匹配时间" min-width="170" prop="matchTime"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button link type="primary" @click="viewDetail(scope.row)">查看详情</el-button>
          <el-button v-if="scope.row.matchStatus !== '匹配成功' && scope.row.matchResult !== '匹配'"
                     link type="primary" @click="manualMatch(scope.row)">
            手动匹配
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {defineEmits, defineProps, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {MatchQueryParams, MatchService} from '@/api/match-service';

const props = defineProps({
  activeTab: {
    type: String,
    default: 'all'
  },
  searchParams: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['view-detail', 'manual-match', 'refresh', 'selection-change']);

// 表格数据
const matchList = ref([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const selectedRows = ref([]);

// 获取匹配记录列表
const getMatchList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: MatchQueryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...props.searchParams as MatchQueryParams
    };

    // 根据当前标签页添加状态筛选
    if (props.activeTab !== 'all') {
      // 将标签页名称转换为对应的状态值
      switch (props.activeTab) {
        case 'success':
          params.matchStatus = '匹配成功';
          break;
        case 'pending':
          params.matchStatus = '待匹配';
          break;
        case 'partial':
          params.matchStatus = '部分匹配';
          break;
        case 'exception':
          params.matchStatus = '匹配异常';
          break;
        case 'match':
          params.matchResult = '匹配';
          break;
        case 'unmatch':
          params.matchResult = '不匹配';
          break;
      }
    }

    const res = await MatchService.getMatchPage(params);
    if (res.code === 200) {
      matchList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || '获取匹配记录失败');
    }
  } catch (error) {
    console.error('获取匹配记录失败', error);
    ElMessage.error('获取匹配记录失败');
  } finally {
    loading.value = false;
  }
};

// 格式化货币
const formatCurrency = (value: number | undefined) => {
  if (!value && value !== 0) return '0.00';
  return Number(value).toFixed(2);
};

// 获取标签类型
const getTagType = (status: string | undefined) => {
  if (!status) return '';

  switch (status) {
    case '匹配成功':
    case '匹配':
      return 'success';
    case '部分匹配':
      return 'warning';
    case '待匹配':
      return 'info';
    case '匹配异常':
    case '不匹配':
      return 'danger';
    default:
      return '';
  }
};

// 选择行
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
  emit('selection-change', selection);
};

// 查看详情
const viewDetail = (row: any) => {
  emit('view-detail', row);
};

// 手动匹配
const manualMatch = (row: any) => {
  emit('manual-match', row);
};

// 删除匹配记录
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该匹配记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await MatchService.deleteMatch(row.id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        await getMatchList(); // 刷新列表
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除匹配记录失败', error);
      ElMessage.error('删除匹配记录失败');
    }
  }).catch(() => {
  });
};

// 分页操作
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getMatchList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getMatchList();
};

// 暴露方法给父组件
defineExpose({
  getMatchList,
  selectedRows,
  refreshData: getMatchList
});
</script>

<style scoped>
.match-records-table {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 